<template>
  <div class="login_container">
    <div class="content">
      <div class="logo">
        <img src="@/assets/logo.jpg">
      </div>
      <van-form @submit="loginSubmit" v-if="pageType == 'login'">
        <van-cell-group inset>
          <van-field v-model="username" name="username" label="用户名" placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]" />
          <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }, {
            validator: (val) => /^\S{6,12}$/.test(val),
            message: '密码必须6~12位，且不能包含空格'
          }]" />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            登录
          </van-button>
        </div>
        <div class="tip">
          还没有账号？<span @click="toRegister" style="color: red;">立即注册</span>
        </div>
      </van-form>

      <van-form @submit="registerSubmit" v-else>
        <van-cell-group inset>
          <van-field v-model="username" name="username" label="用户名" placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]" />
          <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }, {
            validator: (val) => /^\S{6,12}$/.test(val),
            message: '密码必须6~12位，且不能包含空格'
          }]" />
          <van-field v-model="confirmPassword" type="password" name="confirmPassword" label="确认密码" placeholder="确认密码"
            :rules="[
              { required: true, message: '请确认密码' },
              {
                validator: (val) => val === password,
                message: '两次输入的密码不一致'
              }
            ]" />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            注册
          </van-button>
        </div>
        <div class="tip">
          已有账号？<span @click="toLogin" style="color: red;">立即登录</span>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import Cookies from 'js-cookie';
import { setToken } from '../utils/auth';
import { useRouter } from 'vue-router';
import { login, register } from '@/api/user.js';
import { showToast } from 'vant';

const pageType = ref('login'); // 页面类型
const router = useRouter();
const username = ref('');
const password = ref('');
const confirmPassword = ref('');

// 登录
function loginSubmit(data) {
  login(data).then(res => {
    if (res.code == 200) {
      setToken(res.token);
      Cookies.set('username', res.username);
      Cookies.set('userId', res.id);
      router.push({
        path: router.currentRoute.value.query.redirect || '/'
      });
    }
  });
}
// 注册
function registerSubmit(data) {
  if (password.value !== confirmPassword.value) {
    showToast('两次输入的密码不一致');
    return;
  }
  register({ username: data.username, password: data.password })
    .then((res) => {
      if (res.code === 200) {
        // 自动登录
        return login({ username: data.username, password: data.password });
      }
    })
    .then((loginRes) => {
      if (loginRes && loginRes.code === 200) {
        setToken(loginRes.token);
        // Cookies.set('username', loginRes.username);
        Cookies.set('userId', loginRes.id);
        showToast('注册成功');
        router.push({
          path: router.currentRoute.value.query.redirect || '/',
        });
      }
    })
    .catch((err) => {
      showToast(err.message);
    });
}

// 去注册
function toRegister() {
  pageType.value = 'register';
  username.value = '';
  password.value = '';
  confirmPassword.value = '';
}

// 去登录
function toLogin() {
  pageType.value = 'login';
  username.value = '';
  password.value = '';
  confirmPassword.value = '';
}
</script>


<style lang="scss" scoped>
.login_container {
  width: 100%;
  height: 80vh;

  display: flex;
  align-items: center;

  .content {
    width: 100%;
    height: 500px;

    .logo {
      width: 100%;
      height: 100px;
      text-align: center;
      margin-bottom: 100px;

      img {
        width: 100px;
        height: 100px;
        overflow: hidden;
        border-radius: 100%;
      }
    }

    .tip {
      text-align: center;
    }
  }
}
</style>